import { login } from '@/extend/api/user';
import { getToken, setToken, removeToken, removeTokenType, setRoles, deleteRoles, setUserInfo, getUserInfo, removeUserInfo, setCookieTenant, removeCookieTenant, setCurrentOU, removeCurrentOU, getCurrentOU } from '@/lib/auth';
import router, { resetRouter } from '@/lib/router/index';
// import { api_GET_Permissions } from '@/extend/api/swaggerApi/permission-management';
// import { Api_GET_PermissionsQO } from '@/lib/form/swaggerForm';
import { api_GET_UsersCurrent, api_GET_UsersRootOrganizationUnits, api_GET_UsersFirstPermissionOrganizationUnit } from '@/extend/api/swaggerApi/identity';
import { api_GET_EventsManagementUserUserType, api_GET_EventsManagementRegisterId, api_GET_EventsManagementDelegationId } from '@/extend/api/gameswaggerApi/app';
import {
  SiSTKWEventsManagementCreateDelegationInput,
  SiSTKWEventsManagementCreateRegisterInput
} from '@/lib/form/game/swaggerForm';
import { RouterMap } from '@/lib/form/mapData';
import { judgeToLogout } from '@/lib/oidc_fun';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    info: getUserInfo() ? getUserInfo() : '', // 用户信息
    tenantId: '', // 租户id
    avatar: '',
    roles: [], // 权限列表
    currentUserType: null, // 登录用户类型
    // 登录用户信息
    currentUserIndInfo: new SiSTKWEventsManagementCreateRegisterInput(),
    currentUserTeamInfo: new SiSTKWEventsManagementCreateDelegationInput(),
    // 顶级机构信息
    rootUnits: '',
    rootDelegationId: '',
    tags: null,
    firstOrg: '',
    currentOU: getCurrentOU() || ''
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  // 设置权限
  SET_ROLES (state, roles) {
    state.roles = roles;
    setRoles(roles);
  },
  // 设置用户信息
  SET_INFO (state, info) {
    state.info = info;
  },
  // 设置租户id
  SET_TENANTID (state, tenantId) {
    state.tenantId = tenantId;
    setCookieTenant(tenantId);
  },
  // 设置当前登录用户的类型
  SET_CURRENTUSERTYPE (state, type) {
    state.currentUserType = type;
  },
  // 设置当前登录用户的信息
  SET_CURRENTUSERINDINFO (state, info) {
    state.currentUserIndInfo = info;
  },
  SET_CURRENTUSERTEAMINFO (state, info) {
    state.currentUserTeamInfo = info;
  },
  SET_ROOTUNITS (state, datas) {
    state.rootUnits = datas;
    state.rootDelegationId = datas.items && datas.items.length > 0 ? datas.items[0].id : '';
  },
  // 设置用户标签
  SET_USERTAGS (state, datas) {
    state.tags = datas;
    // Vue.set(state, 'tags', datas);
  },
  SET_FIRSTORG (state, datas) {
    state.firstOrg = datas;
  },
  // 设置当前机构id
  SET_CURRENT_OUID (state, datas) {
    state.currentOU = datas;
  }
};

const actions = {
  // user login
  login ({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      console.log(userInfo);
      login(userInfo).then(response => {
        const { data } = response;
        commit('SET_TOKEN', data.token);
        setToken(data.token);
        resolve();
      }).catch(error => {
        reject(error);
      });
    });
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      api_GET_UsersCurrent().then(res => {
        const { name, avatar, tenantId, isEnabled } = res;
        console.log(res);
        if (!isEnabled) {
          clearOut();
          judgeToLogout(window.location.href);
          // resolve('');
        } else {
          setUserInfo(res);
          commit('SET_INFO', res);
          commit('SET_NAME', name);
          commit('SET_TENANTID', tenantId);
          commit('SET_AVATAR', avatar);
          resolve(res);
        }
      }, error => {
        reject(error);
      });
    });
  },

  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      clearOut();
      commit('RESET_STATE');
      commit('SET_ROLES', []);
      commit('SET_CURRENTUSERTYPE', {});
      commit('SET_CURRENTUSERINDINFO', {});
      commit('SET_CURRENTUSERTEAMINFO', {});
      commit('SET_CURRENT_OUID', '');
      // 重置浏览过的页面记录
      dispatch('tagsView/delAllViews', null, { root: true });
      resolve();
      // }).catch(error => {
      //   reject(error);
      // });
    });
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      removeUserInfo();
      removeTokenType();
      deleteRoles();
      commit('RESET_STATE');
      commit('SET_ROLES', []);
      commit('SET_CURRENTUSERTYPE', {});
      commit('SET_CURRENTUSERINDINFO', {});
      commit('SET_CURRENTUSERTEAMINFO', {});
      resolve();
    });
  },
  async changeRoles ({ commit, dispatch }, role) {
    // Dynamically modify permissions
    const token = role + '-token';
    commit('SET_TOKEN', token);
    setToken(token);

    const { roles } = await dispatch('getInfo');
    resetRouter();

    // 获取新权限下的路由表
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true });
    // 添加路由
    router.addRoutes(accessRoutes);

    // 重置浏览过的页面记录
    dispatch('tagsView/delAllViews', null, { root: true });
  },

  getRouter ({ commit, state }) {
    return new Promise((resolve, reject) => {
      const groups = state.info.permissions;
      // 开发中的路由单元
      const _developmentUnit = ['Normal404'];

      // TODO 添加不需要权限验证路由
      const unIdentityRouter = process.env.VUE_APP_DIREVTOR === 'dev' || process.env.VUE_APP_DIREVTOR === 'pro' ? _developmentUnit : ['Normal404'];
      // TODO 可根据角色添加不通特殊权限
      const _defaultRoleRols = [];
      if (state.info.isSuperAdmin) {
        // 无锡中心添加权限
        // 'HallVersionManage' 道馆版本管理
        // 'PlatformIntegral' 平台积分
        // 'Popularity' 人气榜管理
        // 'AppDefaultCustom' 小程序&APP配置
        // 'RegisteredAccountManage' 注册账户管理
        // 'InsuranceChargeSetting' 保险费用设置
        _defaultRoleRols.push('PlatformIntegral', 'CertificateManage', 'HallVersionManage', 'Popularity', 'AppDefaultCustom', 'RegisteredAccountManage', 'InsuranceChargeSetting');
      }
      // 如果登入的用户机构类型是Club 则添加道馆版本购买菜单权限
      const _typeCode = state.info.currentOrganizationUnit.typeCode;
      if (_typeCode === 'Club') {
        // 道馆添加权限
        _defaultRoleRols.push('HallVersionBuy');
      }

      // 如果登入得用户有道馆版本及权限，那么追加通用权限
      const _clubEdit = state.info.organizationUnitEdition;
      if (_clubEdit && _clubEdit.isValid) {
        // 添加道馆通用权限
        _defaultRoleRols.push('HallGeneral');
      }

      // "ProvinceTA"
      const _hasDuanSetting = groups.findIndex(item => item === 'Club.DuanSetting') !== -1;
      const _hasMembershipFeeSetting = groups.findIndex(item => item === 'Club.MembershipFeeSetting') !== -1;

      if (_typeCode === 'ProvinceTA' && _hasDuanSetting && _hasMembershipFeeSetting) {
        _defaultRoleRols.push('DuanAndMembershipFee');
      }

      const routers = [...unIdentityRouter, ..._defaultRoleRols].concat(reDirectRouters(groups));
      commit('SET_ROLES', routers);
      resolve(routers);
    });
  },
  // 获取当前用户注册类型
  getCurrentUserType ({ commit }) {
    return new Promise((resolve, reject) => {
      api_GET_EventsManagementUserUserType().then(res => {
        commit('SET_CURRENTUSERTYPE', res);
        resolve(res);
      }, error => {
        reject(error);
      });
    });
  },
  getSaveCurrentUserType: function ({ commit }, data) {
    commit('SET_CURRENTUSERTYPE', data);
  },
  // 获取当前用户注册 —— 个人
  getCurrentUserIndInfo ({ commit }, data) {
    return new Promise((resolve, reject) => {
      api_GET_EventsManagementRegisterId(data.id).then(res => {
        commit('SET_CURRENTUSERINDINFO', res);
        resolve(res);
      }, error => {
        reject(error);
      });
    });
  },
  getSaveCurrentUserIndInfo: function ({ commit }, info) {
    commit('SET_CURRENTUSERINDINFO', info);
  },
  // 设置用户标签
  getSaveCurrentUserTags: function ({ commit }, info) {
    commit('SET_USERTAGS', info);
  },
  getCurrentUserTeamInfo ({ commit }, data) {
    return new Promise((resolve, reject) => {
      api_GET_EventsManagementDelegationId(data.id).then(res => {
        commit('SET_CURRENTUSERTEAMINFO', res);
        resolve(res);
      }, error => {
        reject(error);
      });
    });
  },
  // 获取当前用户注册 —— 团体
  getSaveCurrentUserTeamInfo: function ({ commit }, info) {
    commit('SET_CURRENTUSERTEAMINFO', info);
  },
  getRootUnits: function ({ commit }) {
    return new Promise((resolve, reject) => {
      api_GET_UsersRootOrganizationUnits().then(res => {
        commit('SET_ROOTUNITS', res);
        resolve(res);
      }, error => {
        console.error(error);
        resolve(false);
      });
    });
  },
  setTenantId: function ({ commit }, data) {
    commit('SET_TENANTID', data);
  },
  getFirstOrg: function ({ commit }) {
    return new Promise((resolve, reject) => {
      api_GET_UsersFirstPermissionOrganizationUnit().then(res => {
        commit('SET_FIRSTORG', res);
        resolve(res);
      }, error => {
        console.error(error);
        resolve(false);
      });
    });
  },
  // 设置当前机构id
  setCurrentOUID: function ({ commit }, data) {
    commit('SET_CURRENT_OUID', data);
    setCurrentOU(data);
  },
  // 清除当前机构
  removeCurrentOUID: function ({ commit }) {
    commit('SET_CURRENT_OUID', '');
    removeCurrentOU();
  }
};

export function clearOut () {
  removeToken(); // must remove  token  first
  removeUserInfo();
  removeTokenType();
  deleteRoles();
  resetRouter();
  removeCookieTenant();
  removeCurrentOU();
}

/**
 * 平级权限列表匹配
 * @param {array} aData 权限列表
 */
function reDirectRouters (aData) {
  const routerMap = new RouterMap();
  const returnData = [];
  aData.forEach((item) => {
    returnData.push(routerMap[item] ? routerMap[item] : item);
  });
  return returnData;
}

/**
 * 获取路由权限配置表
 * @param {array} aData 权限组
 */
export function getRouterList (aData) {
  const routerMap = new RouterMap();
  let returnData = [];
  aData.forEach((item, index) => {
    if (item.permissions && item.permissions.length > 0) {
      returnData = returnData.concat(getRouterList(item.permissions));
    } else {
      returnData.push(routerMap[item.name] ? routerMap[item.name] : item.name);
    }
  });
  return returnData;
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
